package org.dromara.hotel.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MoneyUtils;
import org.dromara.hotel.config.WxHookConfig;
import org.dromara.hotel.domain.TerHotelRooms;
import org.dromara.hotel.domain.vo.TerHotelOrdersVo;
import org.dromara.hotel.domain.vo.TerHotelRoomsVo;
import org.dromara.hotel.mapper.TerHotelOrdersMapper;
import org.dromara.hotel.mapper.TerHotelRoomsMapper;
import org.dromara.hotel.service.IWxMaNoticeService;
import org.dromara.resource.api.RemoteSmsService;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * 微信小程序服务通知
 * @author CKJ
 * @description: 微信小程序服务通知
 * @date 2025/4/18 15:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxMaNoticeServiceImpl implements IWxMaNoticeService {

    private final TerHotelOrdersMapper terHotelOrdersMapper;
    private final TerHotelRoomsMapper terHotelRoomsMapper;
    private final WxHookConfig wxHookConfig;
    @DubboReference
    private final RemoteSmsService remoteSmsService;



    /**
     * 酒店、民宿下单通知
     *
     * @param orderId
     */
    @Override
    public void placeOrder(String orderId) {
        TerHotelOrdersVo terOrderVo=terHotelOrdersMapper.selectVoById(orderId);
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到订单信息");
        }
        TerHotelRoomsVo terHotelRoomsVo=terHotelRoomsMapper.selectVoById(terOrderVo.getRoomId());
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到房间信息");
        }
        String startDate = LocalDateTimeUtil.format(terOrderVo.getStartDate(), "yyyy-MM-dd");
        String endDate = LocalDateTimeUtil.format(terOrderVo.getEndDate(), "yyyy-MM-dd");
        String crateTime = LocalDateTimeUtil.format(terOrderVo.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
        String contentStr = String.format(
                "尊敬的运营同事：\n【%s】新订单已生成，请及时处理！，请及时处理！\n▸ 订单ID：%s\n▸ 客人姓名：%s\n▸ 联系电话：%s\n▸ 入住日期：%s\n▸ 退房日期：%s\n▸ 房型信息：%s\n▸ 下单时间：%s\n▸ 支付金额：￥%s元\n▸ 渠道来源：%s",
                terHotelRoomsVo.getHotelName(),orderId,terOrderVo.getName(),DesensitizedUtil.mobilePhone(terOrderVo.getMobile()), startDate,endDate,terHotelRoomsVo.getRoomType(), crateTime, MoneyUtils.fenToYuanStr(terOrderVo.getPrepayAmount()), terOrderVo.getPaymentMethod());
        JSONObject body=new JSONObject();
        body.putOpt("msgtype","text");
        JSONObject text=new JSONObject();
        text.putOpt("content",contentStr);
        text.putOpt("mentioned_list",new String[]{"@all"});
        body.putOpt("text",text);
        HttpRequest request = HttpUtil.createPost(wxHookConfig.getPlaceOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        request.addHeaders(headers);
        String result = request.body(body.toString()).timeout(2000).execute().body();
        log.info("下单通知返回结果:{}",result);
    }

    /**
     * 清洁打扫通知
     *
     * @param orderId
     */
    @Override
    public void cleanOrder(String orderId) {
        TerHotelOrdersVo terOrderVo=terHotelOrdersMapper.selectVoById(orderId);
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到订单信息");
        }
        TerHotelRoomsVo terHotelRoomsVo=terHotelRoomsMapper.selectVoById(terOrderVo.getRoomId());
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到房间信息");
        }
        String startDate = LocalDateTimeUtil.format(terOrderVo.getStartDate(), "yyyy-MM-dd");
        String endDate = LocalDateTimeUtil.format(terOrderVo.getEndDate(), "yyyy-MM-dd");
        String contentStr = String.format(
                "尊敬的运营同事：\n【%s】客人订单已结束，请及时打扫！\n▸ 订单ID：%s\n▸ 客人姓名：%s\n▸ 联系电话：%s\n▸ 入住日期：%s\n▸ 退房日期：%s\n▸ 入住房间：%s\n▸ 房型信息：%s\n▸ 支付金额：￥%s元\n▸ 渠道来源：%s",
                terHotelRoomsVo.getHotelName(),orderId,terOrderVo.getName(),DesensitizedUtil.mobilePhone(terOrderVo.getMobile()), startDate, endDate,terOrderVo.getRoomNo(),terHotelRoomsVo.getRoomType(), MoneyUtils.fenToYuanStr(terOrderVo.getPrepayAmount()),  terOrderVo.getPaymentMethod());
        JSONObject body=new JSONObject();
        body.putOpt("msgtype","text");
        JSONObject text=new JSONObject();
        text.putOpt("content",contentStr);
        text.putOpt("mentioned_list",new String[]{"@all"});
        body.putOpt("text",text);
        HttpRequest request = HttpUtil.createPost(wxHookConfig.getCleanOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        request.addHeaders(headers);
        String result = request.body(body.toString()).timeout(2000).execute().body();
        log.info("清洁打扫通知返回结果:{}",result);
    }

    /**
     * 将完整日期时间转换为 HH:mm 格式
     * @param fullDateTime 格式如 2025-05-30 18:00:00
     * @return 如 18:00（无效输入返回空字符串）
     */
    private static String toHourMinute(String fullDateTime) {
        if (StrUtil.isBlank(fullDateTime)) {
            return "";
        }
        try {
            return DateUtil.format(
                    DateUtil.parse(fullDateTime),
                    "HH:mm"
            );
        } catch (Exception e) {
            // 异常处理（可记录日志）
            return ""; // 或返回原字符串 fullDateTime
        }
    }
}
